package com.suixun.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.authority.service.UserService;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.suixun.dao.AlarmclocktimesMapper;
import com.suixun.dao.ClassattendancesMapper;
import com.suixun.dao.ClasssilenttimesMapper;
import com.suixun.dao.DevicelistMapper;
import com.suixun.dao.DeviceresubmitMapper;
import com.suixun.dao.LogattendancesMapper;
import com.suixun.dao.MapRegionMapper;
import com.suixun.dao.SchoolattendanceMapper;
import com.suixun.dao.SchoolinfoMapper;
import com.suixun.dao.SchooltimesettingMapper;
import com.suixun.dao.StdDeviceinfoMapper;
import com.suixun.dao.StdIotSimMapper;
import com.suixun.dao.StdObjectinfoMapper;
import com.suixun.dao.StdPeopleObjectMapper;
import com.suixun.dao.StdPeopleinfoMapper;
import com.suixun.dao.StdSimidauthMapper;
import com.suixun.dao.model.PageGrid;
import com.suixun.dao.model.PageQueryModel;
import com.suixun.entity.Alarmclocktimes;
import com.suixun.entity.AlarmclocktimesExample;
import com.suixun.entity.Classattendances;
import com.suixun.entity.ClassattendancesExample;
import com.suixun.entity.Classsilenttimes;
import com.suixun.entity.ClasssilenttimesExample;
import com.suixun.entity.Devicelist;
import com.suixun.entity.DevicelistExample;
import com.suixun.entity.Logattendances;
import com.suixun.entity.LogattendancesExample;
import com.suixun.entity.MapRegion;
import com.suixun.entity.MapRegionExample;
import com.suixun.entity.MapRegionWithBLOBs;
import com.suixun.entity.StdDeviceinfo;
import com.suixun.entity.StdDeviceinfoExample;
import com.suixun.entity.StdIotSim;
import com.suixun.entity.StdIotSimExample;
import com.suixun.entity.StdObjectinfo;
import com.suixun.entity.StdObjectinfoExample;
import com.suixun.entity.StdPeopleObject;
import com.suixun.entity.StdPeopleObjectExample;
import com.suixun.entity.StdSimidauth;
import com.suixun.entity.StdSimidauthExample;
import com.suixun.entity.ext.ExtMapRegion;
import com.suixun.entity.ext.ExtStdObjectinfo;
import com.suixun.entity.ext.ExtStdPeopleObjectinfo;
import com.suixun.entity.ext.FullObjectinfo;
import com.suixun.entity.mongodb.DeviceCache;
import com.suixun.entity.mongodb.SafeRegion;
import com.suixun.entity.page.ExMapRegionPage;
import com.suixun.queue.CMDDeal;
import com.suixun.queue.SMSDeal;
import com.suixun.service.AlarmService;
import com.suixun.service.DeviceService;
import com.suixun.service.ObjectService;
import com.suixun.service.SchoolService;
import com.suixun.service.cache.CacheService;
import com.suixun.service.common.CommonService;
import com.suixun.service.mongodb.DeviceCacheService;
import com.suixun.service.mongodb.SafeRegionService;
import com.suixun.service.mongodb.TrackLogService;
import com.suixun.service.redis.RedisService;
import com.suixun.util.BeanUtil;
import com.suixun.util.StringUtil;


@Service
public class ObjectServiceImpl extends BaseServiceImpl implements ObjectService {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    private StdObjectinfoMapper stdObjectinfoMapper;
    @Resource
    private StdPeopleObjectMapper stdPeopleObjectMapper;
    @Resource
    private StdPeopleinfoMapper stdPeopleinfoMapper;
    @Resource
    private CommonService commonService;
    @Resource
    private StdDeviceinfoMapper stdDeviceinfoMapper;
    @Resource
    private AlarmService alarmService;
    @Resource
    private MapRegionMapper mapRegionMapper;
    @Resource
    private DeviceService deviceService;
    @Resource
    private UserService userService;
    @Resource(name = "safeRegionService")
    private SafeRegionService safeRegionService;
    @Resource
    private TrackLogService trackLogService;
    @Resource
    private ClasssilenttimesMapper classsilenttimesMapper;
    @Resource
    private AlarmclocktimesMapper alarmclocktimesMapper;
    @Resource
    private ClassattendancesMapper classattendancesMapper;
    @Resource
    private LogattendancesMapper logattendancesMapper;
    @Resource
    private SchoolattendanceMapper schoolattendanceMapper;
    @Resource
    private SchooltimesettingMapper schooltimesettingMapper;
    @Resource
    private DeviceresubmitMapper deviceresubmitMapper;
    @Resource
    private DevicelistMapper devicelistMapper;
    @Resource
    private DeviceCacheService deviceCacheService;
    @Resource
    private SchoolService schoolService;
    @Resource
    private CacheService cacheService;
    @Resource(name = "redisService")
    private RedisService redisService;
    @Resource
    private SchoolinfoMapper schoolinfoMapper;
    @Resource
    private SMSDeal sMSDeal;
    @Resource
    private StdIotSimMapper stdIotSimMapper;
    @Resource
    private StdSimidauthMapper stdSimidauthMapper;

    @Override
    public List<ExtStdObjectinfo> getBabys(Integer peopleid, Integer peopletype) {
        List<ExtStdObjectinfo> ents = null;
        try {
            String key = "babys" + '_' + peopleid + '_' + peopletype;
            Object object = redisService.get(key);
            if (object != null) return (List<ExtStdObjectinfo>) object;
            Map<String, String> m = new HashMap<String, String>();
            m.put("peopleid", String.valueOf(peopleid));
            m.put("peopletype", String.valueOf(peopletype));
            List<Map<String, Object>> list =
                    commonService.selectList("StdObjectinfoExtendSql.getObjectinfos", m);
            BeanUtil<ExtStdObjectinfo> beanUtil = new BeanUtil<ExtStdObjectinfo>();
            ents = beanUtil.ListMap2JavaBean(list, ExtStdObjectinfo.class);
            if (ents != null && ents.size() > 0)
                redisService.put(key, ents);
            else
                ents = null;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return ents;
    }



    @Override
    public FullObjectinfo getBabyInfo(Integer peopleid, Integer babyid) {
        String key = "babyobject" + "_" + babyid;
        FullObjectinfo fullObjectinfo = (FullObjectinfo) redisService.get(key);
        if (fullObjectinfo != null) {
            fullObjectinfo.setFlower(alarmService.getFlower(babyid));
          //获取手机号对应的iccid   TODO 卫小宝更新std_iot_sim通知清缓存
            if(fullObjectinfo.getIccid() == null || fullObjectinfo.getIccid().isEmpty()){
                StdIotSimExample example = new StdIotSimExample();
                example.createCriteria().andPhoneEqualTo(fullObjectinfo.getSimid());
                List<StdIotSim> stdIotSims = stdIotSimMapper.selectByExample(example);
                if(stdIotSims != null && stdIotSims.size() > 0)
                    fullObjectinfo.setIccid(stdIotSims.get(0).getIccid());
                
                redisService.put(key, fullObjectinfo);
            }
            return fullObjectinfo;
        }
        StdPeopleObjectExample stdPeopleObjectExample = new StdPeopleObjectExample();
        stdPeopleObjectExample.createCriteria().andPeopleidEqualTo(peopleid)
                .andObjectidEqualTo(babyid);
        List<StdPeopleObject> entsList =
                stdPeopleObjectMapper.selectByExample(stdPeopleObjectExample);
        if (entsList != null && entsList.size() > 0) {
            fullObjectinfo = new FullObjectinfo();
            fullObjectinfo.setFamilystatus(entsList.get(0).getFamilystatus());
            fullObjectinfo.setVersion((long) 0);
            fullObjectinfo.setIspush(true);
            fullObjectinfo.setTimeinterval(10);
            StdObjectinfo stdObjectinfo = stdObjectinfoMapper.selectByPrimaryKey(babyid);
            if (!stdObjectinfo.getIsdeleted()) {
                StdDeviceinfoExample stdDeviceinfoExample = new StdDeviceinfoExample();
                stdDeviceinfoExample.createCriteria().andObjectidEqualTo(babyid)
                        .andIsdeletedEqualTo(0).andIsactiveEqualTo(true);
                List<StdDeviceinfo> list =
                        stdDeviceinfoMapper.selectByExample(stdDeviceinfoExample);
                if (list != null && list.size() > 0) {
                    if (stdObjectinfo.getVersion() != null)
                        fullObjectinfo.setVersion(stdObjectinfo.getVersion().getTime()
                                + fullObjectinfo.getVersion());
                    if (list.get(0).getVersion() != null)
                        fullObjectinfo.setVersion(list.get(0).getVersion().getTime()
                                + fullObjectinfo.getVersion());

                    fullObjectinfo.setBirthday(stdObjectinfo.getBirthday());
                    fullObjectinfo.setBluetooth(list.get(0).getBluetooth());
                    fullObjectinfo.setDeviceid(list.get(0).getDeviceid());
                    fullObjectinfo.setDevicetype(list.get(0).getDevicetype());
                    fullObjectinfo.setStarttime(list.get(0).getStarttime());
                    fullObjectinfo.setEndtime(list.get(0).getEndtime());
                    fullObjectinfo.setVersion(fullObjectinfo.getVersion());
                    fullObjectinfo.setFirewall(list.get(0).getFirewall());
                    fullObjectinfo.setGrade(stdObjectinfo.getGrade());
                    fullObjectinfo.setHeadimg(stdObjectinfo.getHeadimg());
                    fullObjectinfo.setHeight(stdObjectinfo.getHeight());
                    fullObjectinfo.setIsactive(list.get(0).getIsactive());
                    fullObjectinfo.setIspush(entsList.get(0).getIspush());
                    fullObjectinfo.setTimeinterval(entsList.get(0).getTimeinterval());
                    fullObjectinfo.setIsshutdown(list.get(0).getIsshutdown());
                    fullObjectinfo.setMdtid(stdObjectinfo.getMdtid());
                    fullObjectinfo.setObjectid(stdObjectinfo.getObjectid());
                    fullObjectinfo.setObjectname(stdObjectinfo.getObjectname());
                    fullObjectinfo.setPeopleid(stdObjectinfo.getPeopleid());
                    fullObjectinfo.setReportmode(list.get(0).getReportmode());
                    fullObjectinfo.setSchoolid(stdObjectinfo.getSchoolid());
                    fullObjectinfo.setSchoolname(stdObjectinfo.getSchoolname());
                    fullObjectinfo.setSex(stdObjectinfo.getSex());
                    fullObjectinfo.setSimid(stdObjectinfo.getSimid());
                    fullObjectinfo.setStudentid(stdObjectinfo.getStudentid());
                    fullObjectinfo.setStudentname(stdObjectinfo.getStudentname());
                    fullObjectinfo.setWeight(stdObjectinfo.getWeight());
                    fullObjectinfo.setFlower(alarmService.getFlower(babyid));
                    
                    stdPeopleObjectExample = new StdPeopleObjectExample();
                    stdPeopleObjectExample.createCriteria().andObjectidEqualTo(babyid)
                            .andFamilystatusEqualTo("班主任");
                    List<StdPeopleObject> rtn =
                            stdPeopleObjectMapper.selectByExample(stdPeopleObjectExample);
                    if (rtn != null && rtn.size() > 0) {
                        fullObjectinfo.setTeacherid(rtn.get(0).getPeopleid());

                    }
                    StdIotSimExample example = new StdIotSimExample();
                    example.createCriteria().andPhoneEqualTo(stdObjectinfo.getSimid());
                    List<StdIotSim> stdIotSims = stdIotSimMapper.selectByExample(example);
                    if(stdIotSims != null && stdIotSims.size() > 0)
                        fullObjectinfo.setIccid(stdIotSims.get(0).getIccid());
                    redisService.put(key, fullObjectinfo);
                    return fullObjectinfo;
                }
                return null;
            } else
                return null;
        }
        return null;
    }

    /*
     * 获取未激活的手机号，因为手机号是存放在objectinfo表的
     */
    @Override
    public Map getNoActiveObjectinfo(Integer peopleid) {

        StdDeviceinfoExample stdDeviceinfoExample = new StdDeviceinfoExample();
        stdDeviceinfoExample.createCriteria().andPeopleidEqualTo(peopleid).andIsdeletedEqualTo(0)
                .andIsactiveEqualTo(false);
        List<StdDeviceinfo> list = stdDeviceinfoMapper.selectByExample(stdDeviceinfoExample);
        if (list != null && list.size() > 0) {
            Integer objectid = list.get(0).getObjectid();
            Map<String, Object> result = new HashMap<String, Object>();
            result.put("deviceid", list.get(0).getDeviceid());
            StdObjectinfo stdObjectinfo = stdObjectinfoMapper.selectByPrimaryKey(objectid);
            if (stdObjectinfo != null) {
                result.put("telephone", stdObjectinfo.getSimid());
            }
            return result;
        }
        return null;
    }

    @Override
    public Map getNoActiveObjectinfo(Integer peopleid, Integer deviceid) {

        StdDeviceinfoExample stdDeviceinfoExample = new StdDeviceinfoExample();
        stdDeviceinfoExample.createCriteria().andDeviceidEqualTo(deviceid).andIsdeletedEqualTo(0)
                .andIsactiveEqualTo(false);
        List<StdDeviceinfo> list = stdDeviceinfoMapper.selectByExample(stdDeviceinfoExample);
        if (list != null && list.size() > 0) {
            Map<String, Object> result = new HashMap<String, Object>();
            result.put("deviceid", list.get(0).getDeviceid());
            result.put("telephone", "");
            return result;
        }
        return null;
    }


    /*
     * 修改家庭称谓
     */
    @Override
    public Boolean saveFamilystatus(Integer peopleid, Integer objectid, String familystatus) {
        StdPeopleObjectExample stdPeopleObjectExample = new StdPeopleObjectExample();
        stdPeopleObjectExample.createCriteria().andObjectidEqualTo(objectid)
                .andFamilystatusEqualTo(familystatus);
        List<StdPeopleObject> stdPeopleObjects =
                stdPeopleObjectMapper.selectByExample(stdPeopleObjectExample);
        if (stdPeopleObjects != null && stdPeopleObjects.size() > 0) {
            return false;
        }
        stdPeopleObjectExample = new StdPeopleObjectExample();
        stdPeopleObjectExample.createCriteria().andPeopleidEqualTo(peopleid)
                .andObjectidEqualTo(objectid);
        StdPeopleObject stdPeopleObject = new StdPeopleObject();
        stdPeopleObject.setFamilystatus(familystatus);
        stdPeopleObjectMapper.updateByExampleSelective(stdPeopleObject, stdPeopleObjectExample);
        FullObjectinfo fullObjectinfo = this.getBabyInfo(peopleid, objectid);
        String userids = this.getGuardians(fullObjectinfo.getMdtid());
        cacheService.flushBabys(userids);
        // object/saveBaby里清缓存
        return true;
    }

    /*
     * 修改家庭称谓 提供给注册流程
     */
    @Override
    @Caching(evict = {@CacheEvict(value = "onedayCache", key = "'babys' + '_' + #peopleid")})
    public Integer saveFamilystatusForLogon(Integer peopleid, Integer deviceid, String familystatus) {
        StdDeviceinfo stdDeviceinfo = stdDeviceinfoMapper.selectByPrimaryKey(deviceid);
        if (stdDeviceinfo != null) {
            StdPeopleObjectExample stdPeopleObjectExample = new StdPeopleObjectExample();
            stdPeopleObjectExample.createCriteria().andObjectidEqualTo(stdDeviceinfo.getObjectid())
                    .andFamilystatusEqualTo(familystatus);
            List<StdPeopleObject> stdPeopleObjects =
                    stdPeopleObjectMapper.selectByExample(stdPeopleObjectExample);
            if (stdPeopleObjects != null && stdPeopleObjects.size() > 0) {
                return -1;
            }
            stdPeopleObjectExample = new StdPeopleObjectExample();
            stdPeopleObjectExample.createCriteria().andPeopleidEqualTo(peopleid)
                    .andObjectidEqualTo(stdDeviceinfo.getObjectid());
            StdPeopleObject stdPeopleObject = new StdPeopleObject();
            stdPeopleObject.setFamilystatus(familystatus);
            stdPeopleObjectMapper.updateByExampleSelective(stdPeopleObject, stdPeopleObjectExample);
            // 清缓存
            cacheService.flushFullBaby(peopleid, stdDeviceinfo.getObjectid());
            cacheService.flushBabys(this.getGuardians(stdDeviceinfo.getMdtid()));
            return 1;
        } else {
            return 0;
        }
    }

    /*
     * 添加安全区域
     */
    @Override
    public MapRegionWithBLOBs saveSafeRegion(Integer peopleid, Integer objectid, Integer centerlng,
            Integer centerlat, Integer radius, String name, String address) {
        MapRegionWithBLOBs mapRegion = null;
        StdPeopleObjectExample stdPeopleObjectExample = new StdPeopleObjectExample();
        stdPeopleObjectExample.createCriteria().andPeopleidEqualTo(peopleid)
                .andObjectidEqualTo(objectid);
        List<StdPeopleObject> entsList =
                stdPeopleObjectMapper.selectByExample(stdPeopleObjectExample);
        if (entsList != null && entsList.size() > 0) {
            StdObjectinfo stdObjectinfo = stdObjectinfoMapper.selectByPrimaryKey(objectid);
            if (stdObjectinfo != null) {
                String ids = stdObjectinfo.getTrackregionInList().trim();
                List<MapRegion> mapRegions = null;
                if (!ids.isEmpty()) {
                    List<Integer> arralarmids = StringUtil.convertToInteger(ids);
                    if (arralarmids != null) {
                        MapRegionExample mapRegionExample = new MapRegionExample();
                        mapRegionExample.createCriteria().andRegionidIn(arralarmids)
                                .andRegionnameEqualTo(name).andIsdeletedEqualTo((byte) 0);
                        mapRegions = mapRegionMapper.selectByExample(mapRegionExample);
                    }
                }
                if (mapRegions == null || mapRegions.size() == 0) {
                    mapRegion = new MapRegionWithBLOBs();
                    mapRegion.setCenterid(1);
                    mapRegion.setCenterlat(centerlat);
                    mapRegion.setCenterlon(centerlng);
                    mapRegion.setCreatetime(new Date());
                    mapRegion.setHoldid(1);
                    mapRegion.setIsdeleted((byte) 0);
                    mapRegion.setIsobjectuse((byte) 0);
                    mapRegion.setMaptype(1);
                    mapRegion.setMaxlat(centerlat);
                    mapRegion.setMaxlon(centerlng);
                    mapRegion.setMinlat(centerlat);
                    mapRegion.setMinlon(centerlng);
                    mapRegion.setRadius(radius);
                    mapRegion.setRegionname(name);
                    mapRegion.setRegioninfo(address);
                    mapRegion.setRegiontype(1);
                    mapRegion.setUpdatetime(new Date());
                    mapRegionMapper.insert(mapRegion);

                    List<Integer> arralarmids = StringUtil.convertToInteger(ids);
                    if (arralarmids != null) {
                        arralarmids.add(mapRegion.getRegionid());
                        ids = StringUtil.arrayToDelimited(arralarmids.toArray(), ",");
                    } else {
                        ids = mapRegion.getRegionid().toString();
                    }
                    StdObjectinfo ent = new StdObjectinfo();
                    ent.setObjectid(objectid);
                    ent.setTrackregionInList(ids);
                    ent.setTrackregionOutList(ids);
                    StdObjectinfoExample stdObjectinfoExample = new StdObjectinfoExample();
                    stdObjectinfoExample.createCriteria().andObjectidEqualTo(objectid);
                    stdObjectinfoMapper.updateByExampleSelective(ent, stdObjectinfoExample);

                    // 处理mongo缓存
                    try {
                        SafeRegion safeRegion = new SafeRegion();
                        safeRegion.setBabyid(objectid);
                        safeRegion.setCenterlat(centerlat);
                        safeRegion.setCenterlng(centerlng);
                        safeRegion.setCreatetime(new Date());
                        safeRegion.setName(name);
                        safeRegion.setAddress(address != null ? address : "");
                        safeRegion.setRadius(radius);
                        safeRegion.setRegionid(mapRegion.getRegionid());
                        safeRegionService.save(safeRegion);

                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                    }
                }
            }
        }
        return mapRegion;
    }

    /*
     * 修改安全区域
     */
    @Override
    public MapRegionWithBLOBs setSafeRegion(Integer peopleid, Integer objectid, Integer regionid,
            Integer centerlng, Integer centerlat, Integer radius, String name, String address) {
        MapRegionWithBLOBs mapRegion = null;
        StdPeopleObjectExample stdPeopleObjectExample = new StdPeopleObjectExample();
        stdPeopleObjectExample.createCriteria().andPeopleidEqualTo(peopleid)
                .andObjectidEqualTo(objectid);
        List<StdPeopleObject> entsList =
                stdPeopleObjectMapper.selectByExample(stdPeopleObjectExample);
        if (entsList != null && entsList.size() > 0) {
            StdObjectinfo stdObjectinfo = stdObjectinfoMapper.selectByPrimaryKey(objectid);
            if (stdObjectinfo != null) {
                String ids = stdObjectinfo.getTrackregionInList().trim();
                List<MapRegion> mapRegions = null;
                if (!ids.isEmpty()) {
                    List<Integer> arralarmids = StringUtil.convertToInteger(ids);
                    if (arralarmids != null) {
                        arralarmids.remove(regionid);
                        if (arralarmids.size() > 0) {
                            MapRegionExample mapRegionExample = new MapRegionExample();
                            mapRegionExample.createCriteria().andRegionidIn(arralarmids)
                                    .andRegionnameEqualTo(name).andIsdeletedEqualTo((byte) 0);
                            mapRegions = mapRegionMapper.selectByExample(mapRegionExample);
                        }
                    }
                }
                if (mapRegions == null || mapRegions.size() == 0) {
                    mapRegion = new MapRegionWithBLOBs();
                    mapRegion.setRegionid(regionid);
                    mapRegion.setUpdatetime(new Date());
                    mapRegion.setCenterlat(centerlat);
                    mapRegion.setCenterlon(centerlng);
                    mapRegion.setRadius(radius);
                    mapRegion.setRegionname(name);
                    mapRegion.setRegioninfo(address);
                    mapRegionMapper.updateByPrimaryKeySelective(mapRegion);

                    // 处理mongo缓存
                    try {

                        Update update = new Update();
                        update.set("centerlat", mapRegion.getCenterlat())
                                .set("centerlng", mapRegion.getCenterlon())
                                .set("name", mapRegion.getRegionname())
                                .set("address", address != null ? address : "")
                                .set("radius", mapRegion.getRadius());
                        safeRegionService.findAndModify(
                                new Query(Criteria.where("regionid").is(regionid)), update);

                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                    }
                }
            }
        }
        return mapRegion;
    }

    @Override
    @Caching(evict = {@CacheEvict(value = "onedayCache", key = "'saferegions' + '_' + #objectid + '_1'")})
    public Boolean deleteSafeRegions(Integer peopleid, Integer objectid, String regionids) {
        List<Integer> arrregionids = StringUtil.convertToInteger(regionids);
        StdPeopleObjectExample stdPeopleObjectExample = new StdPeopleObjectExample();
        stdPeopleObjectExample.createCriteria().andPeopleidEqualTo(peopleid)
                .andObjectidEqualTo(objectid);
        List<StdPeopleObject> entsList =
                stdPeopleObjectMapper.selectByExample(stdPeopleObjectExample);
        if (entsList != null && entsList.size() > 0) {
            StdObjectinfo stdObjectinfo = stdObjectinfoMapper.selectByPrimaryKey(objectid);
            if (stdObjectinfo != null) {
                String oldids = stdObjectinfo.getTrackregionInList();
                List<Integer> arroldregionids = StringUtil.convertToInteger(oldids);
                arroldregionids.removeAll(arrregionids);
                String ids = StringUtil.arrayToDelimited(arroldregionids.toArray());
                // 修改objectInfos表的数据
                StdObjectinfo ent = new StdObjectinfo();
                ent.setTrackregionInList(ids);
                ent.setTrackregionOutList(ids);
                StdObjectinfoExample stdObjectinfoExample = new StdObjectinfoExample();
                stdObjectinfoExample.createCriteria().andObjectidEqualTo(objectid)
                        .andIsdeletedEqualTo(false);
                stdObjectinfoMapper.updateByExampleSelective(ent, stdObjectinfoExample);
            }
            MapRegionExample mapRegionExample = new MapRegionExample();
            mapRegionExample.createCriteria().andRegionidIn(arrregionids);
            mapRegionMapper.deleteByExample(mapRegionExample);

            // 处理mongo缓存
            safeRegionService.findAndRemove(new Query(Criteria.where("regionid").in(arrregionids)));
        }
        return true;
    }

    @Override
    public ExMapRegionPage getSafeRegionsPaged(Integer peopleid, Integer objectid,
            Integer pageIndex, Integer pageSize) {
        pageSize = 1000;

        // 分页获取
        StdPeopleObjectExample stdPeopleObjectExample = new StdPeopleObjectExample();
        stdPeopleObjectExample.createCriteria().andPeopleidEqualTo(peopleid)
                .andObjectidEqualTo(objectid);
        List<StdPeopleObject> entsList =
                stdPeopleObjectMapper.selectByExample(stdPeopleObjectExample);
        if (entsList != null && entsList.size() > 0) {
            StdObjectinfo stdObjectinfo = stdObjectinfoMapper.selectByPrimaryKey(objectid);
            if (stdObjectinfo != null) {
                String ids = stdObjectinfo.getTrackregionInList().trim();
                List<Integer> arralarmids = StringUtil.convertToInteger(ids);
                Map<String, String> m = new HashMap<String, String>();
                m.put("peopleid", String.valueOf(peopleid));
                m.put("objectid", String.valueOf(objectid));
                if (arralarmids != null && arralarmids.size() > 0)
                    ids = StringUtil.arrayToDelimited(arralarmids.toArray());
                else
                    ids = "0";
                m.put("regionids", ids);
                PageQueryModel pqm = new PageQueryModel(pageIndex, pageSize, "regionid", "desc");
                pqm.setQueryParam(m);
                PageGrid pageGrid =
                        this.commonService.pageForObject(
                                "RptMapRegionExtendSql.getSafeRegionListPage", pqm);
                BeanUtil<ExtMapRegion> beanUtil = new BeanUtil<ExtMapRegion>();
                List<ExtMapRegion> ents = null;
                try {
                    ents = beanUtil.ListMap2JavaBean(pageGrid.getRows(), ExtMapRegion.class);
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
                if (ents != null && ents.size() > 0) {
                    ExMapRegionPage exMapRegionPage = new ExMapRegionPage();
                    exMapRegionPage.setInfos(ents);
                    exMapRegionPage.setPagecount(pageGrid.getTotal());
                    exMapRegionPage.setRecordcount(pageGrid.getRecords());
                    return exMapRegionPage;
                }
                return null;
            }
        }
        return null;
    }

    @Override
    public MapRegion getSafeRegion(Integer peopleid, Integer objectid, Integer regionid) {
        StdPeopleObjectExample stdPeopleObjectExample = new StdPeopleObjectExample();
        stdPeopleObjectExample.createCriteria().andPeopleidEqualTo(peopleid)
                .andObjectidEqualTo(objectid);
        List<StdPeopleObject> entsList =
                stdPeopleObjectMapper.selectByExample(stdPeopleObjectExample);
        if (entsList != null && entsList.size() > 0) {
            StdObjectinfo stdObjectinfo = stdObjectinfoMapper.selectByPrimaryKey(objectid);
            if (stdObjectinfo != null) {
                String ids = stdObjectinfo.getTrackregionInList().trim();
                if (ids.contains("," + regionid + ",")) {
                    MapRegion mapRegion = mapRegionMapper.selectByPrimaryKey(regionid);
                    if (mapRegion != null) {
                        return mapRegion;
                    }
                    return null;
                }
            }
        }
        return null;
    }


    /*
     * 获取监护人列表
     */
    @Override
    public List<ExtStdPeopleObjectinfo> getGuardians(Integer peopleid, Integer babyid) {
        List<ExtStdPeopleObjectinfo> guardians = null;
        FullObjectinfo fullObjectinfo = this.getBabyInfo(peopleid, babyid);
        if (fullObjectinfo != null) {
            Map<String, String> m = new HashMap<String, String>();
            m.put("objectid", String.valueOf(babyid));
            PageQueryModel pqm = new PageQueryModel(1, 20, "", "");
            pqm.setDoCount(false);
            pqm.setQueryParam(m);
            PageGrid pageGrid =
                    this.commonService.pageForObject("StdObjectinfoExtendSql.getGuardianList", pqm);
            List<Map<String, Object>> datas = pageGrid.getRows();
            if (datas != null) {
                guardians = new ArrayList<ExtStdPeopleObjectinfo>();
                for (Map<String, Object> mapdata : datas) {
                    ExtStdPeopleObjectinfo guardian = new ExtStdPeopleObjectinfo();
                    guardian.setBabyid(Integer.valueOf(mapdata.get("objectid").toString()));
                    guardian.setFamilystatus(mapdata.get("familystatus") == null
                            || mapdata.get("familystatus").equals("") ? "家长" : mapdata.get(
                            "familystatus").toString());
                    guardian.setGuardianid(Integer.valueOf(mapdata.get("peopleid").toString()));
                    // 获取管理员ID
                    guardian.setUserid(fullObjectinfo.getPeopleid());
                    guardian.setTelephone(mapdata.get("peopletel").toString());
                    guardian.setIspush(mapdata.get("ispush") == null ? true : Boolean
                            .valueOf(mapdata.get("ispush").toString()));
                    guardian.setTimeinterval(mapdata.get("timeinterval") == null ? 10 : Integer
                            .valueOf(mapdata.get("timeinterval").toString()));
                    if (mapdata.get("headimg") != null)
                        guardian.setHeadimg(mapdata.get("headimg").toString());
                    else
                        guardian.setHeadimg("");
                    guardians.add(guardian);
                }
            }
        }
        return guardians;
    }

    @Override
    public Integer cancelBaby2(Integer peopleid, Integer babyid, Integer guardianid) {
        FullObjectinfo fullObjectinfo = this.getBabyInfo(peopleid, babyid);
        if (peopleid.equals(fullObjectinfo.getPeopleid())) {
            fullObjectinfo = this.getBabyInfo(guardianid, babyid);
            if (fullObjectinfo != null) {
                StdPeopleObjectExample stdPeopleObjectExample = new StdPeopleObjectExample();
                stdPeopleObjectExample.createCriteria().andPeopleidEqualTo(guardianid)
                        .andObjectidEqualTo(babyid);
                stdPeopleObjectMapper.deleteByExample(stdPeopleObjectExample);

                // 清缓存
                cacheService.flushBabys(this.getGuardians(fullObjectinfo.getMdtid()));
                cacheService.flushFullBaby(peopleid, babyid);
                // mongodb cache
                cacheService.refreshDeviceCache(fullObjectinfo.getMdtid());
                return 1;
            } else {
                return -2;
            }
        } else {
            return -1;
        }
    }

    /*
     * 管理员取消关注
     */
    @Override
    public Integer cancelBaby2(Integer peopleid, Integer babyid) {
        FullObjectinfo fullObjectinfo = this.getBabyInfo(peopleid, babyid);
        if (fullObjectinfo != null) {
            // 非管理员操作退出
            if (peopleid.equals(fullObjectinfo.getPeopleid())) {
                String tempMdiid = fullObjectinfo.getMdtid();
                DevicelistExample devicelistExample = new DevicelistExample();
                devicelistExample.createCriteria().andMdtidEqualTo(tempMdiid);
                Devicelist devicelist = null;
                List<Devicelist> devicelists = devicelistMapper.selectByExample(devicelistExample);
                if (devicelists != null && devicelists.size() > 0) {
                    devicelist = devicelists.get(0);
                }
                // 重置devicelists表数据
                if (devicelist != null) {
                    if (devicelist.getDevicetype().equals(1)) {
                        devicelist = new Devicelist();
                        devicelist.setIsinit(false);
                    } else {
                        devicelist = new Devicelist();
                        devicelist.setIsinit(false);
                        devicelist.setStatus(0);
                    }
                    devicelist.setUpdatetime(new Date());
                    devicelistMapper.updateByExampleSelective(devicelist, devicelistExample);
                }
                // 清缓存
                cacheService.flushBabys(this.getGuardians(tempMdiid));
                cacheService.flushFullBaby(peopleid, babyid);

                StdPeopleObjectExample stdPeopleObjectExample = new StdPeopleObjectExample();
                stdPeopleObjectExample.createCriteria().andObjectidEqualTo(babyid);
                stdPeopleObjectMapper.deleteByExample(stdPeopleObjectExample);

                StdObjectinfo stdObjectinfo = new StdObjectinfo();
                stdObjectinfo.setObjectid(babyid);
                stdObjectinfo.setIsdeleted(true);
                stdObjectinfoMapper.updateByPrimaryKeySelective(stdObjectinfo);

                StdDeviceinfoExample stdDeviceinfoExample = new StdDeviceinfoExample();
                stdDeviceinfoExample.createCriteria().andObjectidEqualTo(babyid)
                        .andIsdeletedEqualTo(0);
                List<StdDeviceinfo> list =
                        stdDeviceinfoMapper.selectByExample(stdDeviceinfoExample);
                if (list != null && list.size() > 0) {
                    Integer deviceid = list.get(0).getDeviceid();

                    StdDeviceinfo stdDeviceinfo = new StdDeviceinfo();
                    stdDeviceinfo.setUpdatetime(new Date());
                    stdDeviceinfo.setPeopleid(0);
                    stdDeviceinfo.setObjectid(0);
                    stdDeviceinfoMapper.updateByExampleSelective(stdDeviceinfo,
                            stdDeviceinfoExample);

                    // 推送管理员解绑
                    DeviceCache deviceCache = null;
                    List<DeviceCache> deviceCaches =
                            deviceCacheService
                                    .find(new Query(Criteria.where("mdtid").is(tempMdiid)).limit(1));
                    if (deviceCaches == null || deviceCaches.size() == 0) {} else {
                        deviceCache = deviceCaches.get(0);
                    }
                    if (deviceCache != null)
                        CMDDeal.sendcancel("cancelbaby", peopleid, babyid,
                                deviceCache.getTelephones(), tempMdiid, deviceCache.getBabyname());
                }
                cacheService.refreshDeviceCache(tempMdiid, peopleid, babyid, true);
                return 1;
            } else {
                return -1;
            }
        } else {
            return -2;
        }
    }

    @Override
    public ExtStdPeopleObjectinfo getGuardian(Integer peopleid, Integer babyid, Integer guardianid) {
        ExtStdPeopleObjectinfo guardian = null;
        FullObjectinfo fullObjectinfo = this.getBabyInfo(peopleid, babyid);
        if (fullObjectinfo != null) {
            Map<String, String> m = new HashMap<String, String>();
            m.put("objectid", String.valueOf(babyid));
            m.put("guardianid", String.valueOf(guardianid));
            PageQueryModel pqm = new PageQueryModel(1, 20, "", "");
            pqm.setDoCount(false);
            pqm.setQueryParam(m);
            PageGrid pageGrid =
                    this.commonService.pageForObject("StdObjectinfoExtendSql.getGuardian", pqm);
            List<Map<String, Object>> datas = pageGrid.getRows();
            if (datas != null) {
                guardian = new ExtStdPeopleObjectinfo();
                Map<String, Object> mapdata = datas.get(0);

                guardian.setBabyid(Integer.valueOf(mapdata.get("objectid").toString()));
                if (mapdata.get("familystatus") != null)
                    guardian.setFamilystatus(mapdata.get("familystatus").toString());
                else {
                    guardian.setFamilystatus("家长");
                }
                guardian.setGuardianid(Integer.valueOf(mapdata.get("peopleid").toString()));
                // 获取管理员ID
                guardian.setUserid(fullObjectinfo.getPeopleid());
                if (mapdata.get("peopletel") != null)
                    guardian.setTelephone(mapdata.get("peopletel").toString());
                else
                    guardian.setTelephone("");

                guardian.setIspush(mapdata.get("ispush") == null ? true : Boolean.valueOf(mapdata
                        .get("ispush").toString()));
                guardian.setTimeinterval(mapdata.get("timeinterval") == null ? 10 : Integer
                        .valueOf(mapdata.get("timeinterval").toString()));

                if (mapdata.get("headimg") != null)
                    guardian.setHeadimg(mapdata.get("headimg").toString());
                else
                    guardian.setHeadimg("");
            }
        }
        return guardian;
    }



    /*
     * 取消关注
     */
    @Override
    public Boolean cancelBaby(Integer peopleid, Integer babyid) {
        FullObjectinfo fullObjectinfo = this.getBabyInfo(peopleid, babyid);
        if (fullObjectinfo != null && !fullObjectinfo.getPeopleid().equals(peopleid)) {
            StdPeopleObjectExample stdPeopleObjectExample = new StdPeopleObjectExample();
            stdPeopleObjectExample.createCriteria().andPeopleidEqualTo(peopleid)
                    .andObjectidEqualTo(babyid);
            stdPeopleObjectMapper.deleteByExample(stdPeopleObjectExample);

            // 清缓存
            cacheService.flushBabys(this.getGuardians(fullObjectinfo.getMdtid()));
            cacheService.flushFullBaby(peopleid, babyid);
            // mongodb cache
            cacheService.refreshDeviceCache(fullObjectinfo.getMdtid());
            return true;
        } else {
            return false;
        }
    }

    @Override
    public List<Logattendances> getAttendanceLogs(Integer peopleid, Integer objectid,
            Date starttime, Date endtime) {

        LogattendancesExample logattendancesExample = new LogattendancesExample();
        /*
         * Calendar c = Calendar.getInstance(); c.setTime(date); c.add(c.DATE, 1);
         */
        logattendancesExample.createCriteria().andObjectidEqualTo(objectid)
                .andAttendancetimeGreaterThan(starttime).andAttendancetimeLessThan(endtime);
        logattendancesExample.setOrderByClause("id desc");
        List<Logattendances> ents = logattendancesMapper.selectByExample(logattendancesExample);
        if (ents != null) {
            return ents;
        }
        return null;
    }


    @Override
    @CacheEvict(value = "onedayCache", key = "'alarmclocks' + '_' + #peopleid + '_' + #objectid")
    public Boolean saveAlarmclock(Integer peopleid, Integer objectid, Integer alarmid,
            String alarmtime, Integer mode, String alarmname, String opencycle) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        if (alarmname == null || alarmname == "") {
            alarmname = "闹铃";
        }
        if (alarmid != null && alarmid > 0) {
            AlarmclocktimesExample example = new AlarmclocktimesExample();
            example.createCriteria().andPeopleidEqualTo(peopleid).andObjectidEqualTo(objectid)
                    .andIdEqualTo(alarmid);
            Alarmclocktimes ent = new Alarmclocktimes();
            ent.setAlarmtime(sdf.parse(alarmtime));
            ent.setMode(mode);
            ent.setOpencycle(opencycle);
            ent.setAlarmname(alarmname);
            alarmclocktimesMapper.updateByExampleSelective(ent, example);
        } else {
            AlarmclocktimesExample alarmclocktimesExample = new AlarmclocktimesExample();
            alarmclocktimesExample.createCriteria().andPeopleidEqualTo(peopleid)
                    .andObjectidEqualTo(objectid);
            int count = alarmclocktimesMapper.countByExample(alarmclocktimesExample);
            if (count >= 5) {
                throw new Exception("闹钟个数不得大于5个");
            }
            Alarmclocktimes ent = new Alarmclocktimes();
            ent.setAlarmtime(sdf.parse(alarmtime));
            ent.setMode(mode);
            ent.setOpencycle(opencycle);
            ent.setObjectid(objectid);
            ent.setPeopleid(peopleid);
            ent.setAlarmname(alarmname);
            ent.setAddtime(new Date());
            alarmclocktimesMapper.insert(ent);
        }
        return true;
    }

    @Override
    @CacheEvict(value = "onedayCache", key = "'alarmclocks' + '_' + #peopleid + '_' + #objectid")
    public Boolean deleteAlarmClocks(Integer peopleid, Integer objectid, String alarmids) {
        AlarmclocktimesExample alarmclocktimesExample = new AlarmclocktimesExample();
        List<Integer> arralarmids = StringUtil.convertToInteger(alarmids);
        alarmclocktimesExample.createCriteria().andPeopleidEqualTo(peopleid)
                .andObjectidEqualTo(objectid).andIdIn(arralarmids);
        alarmclocktimesMapper.deleteByExample(alarmclocktimesExample);
        return true;
    }

    @Override
    public Boolean syncAlarmClocks(Integer peopleid, Integer objectid) {
        SimpleDateFormat sdf = null;
        ObjectMapper mapper = new ObjectMapper();
        mapper.getFactory().configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true);
        StdObjectinfo stdObjectinfo = stdObjectinfoMapper.selectByPrimaryKey(objectid);
        try {
            if (stdObjectinfo != null) {
                /*
                 * if (!stdObjectinfo.getPeopleid().equals(peopleid)) { throw new
                 * APIException(APICode.API_10127.setCustomMsg("仅允许管理员操作"), null); }
                 */
                AlarmclocktimesExample alarmclocktimesExample = new AlarmclocktimesExample();
                alarmclocktimesExample.createCriteria().andPeopleidEqualTo(peopleid)
                        .andObjectidEqualTo(objectid).andModeNotEqualTo(0);
                List<Alarmclocktimes> ents =
                        alarmclocktimesMapper.selectByExample(alarmclocktimesExample);
                if (ents != null) {
                    sdf = new SimpleDateFormat("HHmm");
                    List<Map<String, String>> listresult = new ArrayList<Map<String, String>>();
                    for (Alarmclocktimes alarmclocktimes : ents) {
                        String time = sdf.format(alarmclocktimes.getAlarmtime());
                        Map<String, String> mapresult = new HashMap<String, String>();
                        mapresult.put("alarmtime", time);
                        mapresult.put("alarmname", alarmclocktimes.getAlarmname());
                        mapresult.put("mode", alarmclocktimes.getMode().toString());
                        mapresult.put("opencycle",
                                alarmclocktimes.getOpencycle().replaceAll(",", ""));
                        listresult.add(mapresult);
                    }
                    CMDDeal.sendalarmclock(mapper.writeValueAsString(listresult),
                            stdObjectinfo.getMdtid(), peopleid, objectid);
                }
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    @Override
    public List<Alarmclocktimes> getAlarmclocks(Integer peopleid, Integer objectid) {

        AlarmclocktimesExample alarmclocktimesExample = new AlarmclocktimesExample();
        alarmclocktimesExample.createCriteria().andPeopleidEqualTo(peopleid)
                .andObjectidEqualTo(objectid);
        List<Alarmclocktimes> ents = alarmclocktimesMapper.selectByExample(alarmclocktimesExample);
        if (ents != null) {
            return ents;
        }
        return null;
    }

    @Override
    public List<Classattendances> getAttendances(Integer peopleid, Integer objectid) {

        ClassattendancesExample classattendancesExample = new ClassattendancesExample();
        classattendancesExample.createCriteria().andObjectidEqualTo(objectid);
        List<Classattendances> ents =
                classattendancesMapper.selectByExample(classattendancesExample);
        if (ents != null) {
            return ents;
        }
        return null;
    }


    @Override
    @CacheEvict(value = "onedayCache", key = "'classattendances' + '_' + #objectid")
    public Boolean saveAttendance(Integer peopleid, Integer objectid, Integer alarmid,
            String alarmtime, Integer type, Boolean isclose) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");

        if (alarmid != null && alarmid > 0) {
            ClassattendancesExample example = new ClassattendancesExample();
            example.createCriteria().andObjectidEqualTo(objectid).andIdEqualTo(alarmid);
            Classattendances ent = new Classattendances();
            ent.setChecktime(sdf.parse(alarmtime));
            ent.setIsclose(isclose);
            classattendancesMapper.updateByExampleSelective(ent, example);
        } else {
            ClassattendancesExample example = new ClassattendancesExample();
            example.createCriteria().andObjectidEqualTo(objectid).andTypeEqualTo(type);
            int count = classattendancesMapper.countByExample(example);
            if (count >= 1) {
                throw new Exception();
            }
            Classattendances ent = new Classattendances();
            ent.setChecktime(sdf.parse(alarmtime));
            ent.setType(type);
            ent.setObjectid(objectid);
            ent.setPeopleid(0);
            ent.setIsclose(isclose);
            classattendancesMapper.insert(ent);
        }
        return true;
    }

    @Override
    @CacheEvict(value = "onedayCache", key = "'classattendances' + '_' + #objectid")
    public Boolean deleteAttendances(Integer peopleid, Integer objectid, String alarmids) {
        ClassattendancesExample classattendancesExample = new ClassattendancesExample();
        List<Integer> arralarmids = StringUtil.convertToInteger(alarmids);
        classattendancesExample.createCriteria().andObjectidEqualTo(objectid).andIdIn(arralarmids);
        classattendancesMapper.deleteByExample(classattendancesExample);
        return true;
    }

    @Override
    public String getGuardians(String mdtid) {
        DeviceCache deviceCache = null;
        List<DeviceCache> deviceCaches =
                deviceCacheService.find(new Query(Criteria.where("mdtid").is(mdtid)).limit(1));
        if (deviceCaches == null || deviceCaches.size() == 0) {} else {
            deviceCache = deviceCaches.get(0);
        }
        if (deviceCache == null) return "";
        if (deviceCache.getUserids() != null) {
            List<Integer> peopleids = StringUtil.convertToInteger(deviceCache.getUserids());
            if (peopleids != null) {
                return StringUtils.join(peopleids, ",");
            }
            return "";
        }
        return "";
    }



    /**
     * 保存 设备 课堂静音设置
     * 
     * @param deviceInfo
     * @return
     * @throws ParseException
     * @throws JsonProcessingException
     */
    @Override
    @Transactional(value = "transactionManager", isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public Boolean saveClassSilentInfo(Integer peopleid, Integer objectid, String starttimeAM,
            String endtimeAM, String starttimePM, String endtimePM, String opencycle, String mdtid)
            throws ParseException, JsonProcessingException {

        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        ClasssilenttimesExample classsilenttimesExample = new ClasssilenttimesExample();
        classsilenttimesExample.createCriteria().andPeopleidEqualTo(peopleid)
                .andObjectidEqualTo(objectid);
        List<Classsilenttimes> rtn =
                classsilenttimesMapper.selectByExample(classsilenttimesExample);
        if (rtn != null && rtn.size() > 0) {
            // 设备已存在 按照主键更新
            for (Classsilenttimes classilenttime : rtn) {
                if (classilenttime.getMode().equals(0)) {
                    // 0 上午 1 下午
                    classilenttime.setStarttime(sdf.parse(starttimeAM));
                    classilenttime.setEndtime(sdf.parse(endtimeAM));
                } else {
                    classilenttime.setStarttime(sdf.parse(starttimePM));
                    classilenttime.setEndtime(sdf.parse(endtimePM));
                }
                classilenttime.setOpencycle(opencycle);
                classsilenttimesMapper.updateByPrimaryKey(classilenttime);
            }
        } else {
            Classsilenttimes ent = new Classsilenttimes();
            ent.setStarttime(sdf.parse(starttimeAM));
            ent.setEndtime(sdf.parse(endtimeAM));
            ent.setMode(0);// 0 上午 1 下午
            ent.setObjectid(objectid);
            ent.setPeopleid(peopleid);
            ent.setOpencycle(opencycle);
            classsilenttimesMapper.insert(ent);
            ent = new Classsilenttimes();
            ent.setStarttime(sdf.parse(starttimePM));
            ent.setEndtime(sdf.parse(endtimePM));
            ent.setMode(1);// 0 上午 1 下午
            ent.setObjectid(objectid);
            ent.setPeopleid(peopleid);
            ent.setOpencycle(opencycle);
            classsilenttimesMapper.insert(ent);
        }


        Map<Integer, List<String>> mapresult = new HashMap<Integer, List<String>>();
        int index = 1;
        for (String week : opencycle.split("\\,")) {
            List<String> arr = new ArrayList<String>();
            String time = starttimeAM.replaceAll("\\:", "") + endtimeAM.replaceAll("\\:", "");
            arr.add(time);
            time = starttimePM.replaceAll("\\:", "") + endtimePM.replaceAll("\\:", "");
            arr.add(time);
            if (week.equals("1")) {
                mapresult.put(index, arr);
            }
            index++;
        }
        ObjectMapper mapper = new ObjectMapper();
        CMDDeal.sendclasssilent(mapper.writeValueAsString(mapresult), mdtid, peopleid, objectid);

        return true;
    }


    /**
     * 根据 宝贝id根家长id 获取课堂静音设置详情
     * 
     * @param userid
     * @param babyid
     * @return
     */
    @Override
    public List<Classsilenttimes> getClassSilentInfo(Integer peopleid, Integer objectid) {

        ClasssilenttimesExample classsilenttimesExample = new ClasssilenttimesExample();
        classsilenttimesExample.createCriteria().andPeopleidEqualTo(peopleid)
                .andObjectidEqualTo(objectid);
        List<Classsilenttimes> rtn =
                classsilenttimesMapper.selectByExample(classsilenttimesExample);
        if (rtn != null && rtn.size() > 0) {
            // 设备已存在 按照主键更新
            return rtn;
        }
        return null;
    }
    
    @Override
	public StdSimidauth getSimidAuthBySimid(String simid) {
		if (StringUtils.isEmpty(simid)) {
			return null;
		}
		StdSimidauthExample stdSimidauthExample = new StdSimidauthExample();
		stdSimidauthExample.createCriteria().andSimidEqualTo(simid);
		List<StdSimidauth> authList = stdSimidauthMapper.selectByExample(stdSimidauthExample);
		if (CollectionUtils.isEmpty(authList)) {
			return null;
		}
		return authList.get(0);
	}
}
